import CustomError from "../utils/CustomError";
import Storage from "../utils/Storage";
import {optionsToString, isType} from "../utils/Util"

/*
* 请求栈
* */
let requestList = [];

/*
* 错误码code处理
* */
async function _codeFunc  (res, isCheckExpired) {
    switch (parseInt(res.data.code)) {
        case 200 :
            return res.data.data;
        case 401:
            if (isCheckExpired) return new CustomError({
                errCode: res.data.code,
                errMsg: res.data.message
            });
            await _showModal();
            const app = getApp();
            if (!app.globalData.isLoginExpired) {
                const pages = getCurrentPages();
                let currentContext = pages[pages.length - 1];
                let currentRoute = currentContext.route;
                let params = currentContext.options;
                app.globalData.isLoginExpired = true;
                Storage.setStorageSync("token.page", "/" + currentRoute + optionsToString(params))
                wx.redirectTo({ //关闭当前页面 跳转tab页
                    url: "/pages/user/login/index/index",
                    complete: function () {
                        app.globalData.isLoginExpired = false
                    }
                }); 
            }
            return new CustomError({
                errCode: res.data.code,
                errMsg: res.data.message
            })
        default:
            return new CustomError({
                errCode: res.data.code,
                errMsg: res.data.message
            })
    }
}

/*
* 模态框
* */
function _showModal() {
    return new Promise(function (resolve) {
        wx.showModal({
            title: "提示",
            content: "请先登录",
            showCancel: false,
            complete: function () {
                resolve()
            }
        })
    })
}

/*
* 防重复请求
* 每次请求requestList栈记录
* 如果请求接口且请求参数一致 则认为是同一个请求
* */
function _preventRepeat(params) {
    let {url, data = {}} = params;
    let findInx;
    return {
        getter: function () {
            findInx = requestList.findIndex(function (item) {
                return url === item.url && JSON.stringify(data) === JSON.stringify(item.data)
            });
            if (findInx >= 0) { //存在
                return parseInt(findInx)
            } else {
                requestList.push({
                    url,
                    data
                })
                return false
            }
        },
        setter: function () {
            findInx = requestList.findIndex(function (item) {
                return url === item.url && JSON.stringify(data) === JSON.stringify(item.data)
            });
            requestList.splice(findInx, 1);
        }
    }

}

/*
* 请求体request
*
* */
function request (params, isCheckExpired) {
    return new Promise(function (resolve, reject) {
        let {url, header = {}} = params,
            token = Storage.getStorageSync("token");
        let preventRepeat = _preventRepeat(params);
        if (isType(preventRepeat.getter(), "Number")) { //重复请求
            // reject(new Error("repeat request"));
            return false
        }
        if (!url) { //url 不存在
            reject(new Error("request.url is not found"));
            return false
        }
        if (token.isExpired) { //token已过期
            reject(new Error("request fail: token expired"));
            return false
        }
        token ? header.Authorization = "Bearer " + token.value : null;
        Object.keys(header).length > 0 ? params.header = header : null;
        wx.request({
            ...params,
            success: async function (res) {
                let _res = await _codeFunc(res, isCheckExpired) || {};
                !_res.errCode ? resolve(_res) : (_res.errCode !== "401" ? reject(_res) : null);
            },
            fail: function (err) {
                reject(err)
            },
            complete: function () {
                preventRepeat.setter();
            }
        })
    })
}



module.exports = {request}
